package com.leyou.search.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.pojo.PageResult;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.entity.*;
import com.leyou.search.dto.GoodsDTO;
import com.leyou.search.dto.SearchRequest;
import com.leyou.search.entity.Goods;
import com.leyou.search.repository.SearchRepository;
import com.leyou.search.utils.HighlightUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.ScoreSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchService {

    @Autowired
    private SearchRepository searchRepository;

    @Autowired
    private ElasticsearchTemplate esTemplate;

    @Autowired
    private ItemClient itemClient;

    /**
     * 将SpuDTO对象转成Goods对象
     */
    public Goods buildGoods(SpuDTO spuDTO){
        //根据spuId查询Sku集合
        List<Sku> skus = itemClient.findSkusBySpuId(spuDTO.getId());
        //提供一个map的集合来存放需要的sku属性
        List<Map<String, Object>> skuList = new ArrayList<>();
        skus.forEach(sku -> {
            Map<String, Object> skuMap = new HashMap<>();
            skuMap.put("id", sku.getId());
            skuMap.put("image", sku.getImages());
            skuMap.put("title", sku.getTitle().substring(spuDTO.getName().length()));
            skuMap.put("price", sku.getPrice());
            skuList.add(skuMap);
        });

        //得到所有sku的价格的set集合
        Set<Long> prices = skus.stream().map(Sku::getPrice).collect(Collectors.toSet());

        //得到减索字段
        String all = spuDTO.getBrandName()+spuDTO.getCategoryName()+
                skus.stream().map(Sku::getTitle).collect(Collectors.joining());

        //得到动态过滤条件
        Map<String, Object> filterParamMap = new HashMap<>();
        //通过分类id查询出当前分类下所有参与搜索的规格参数集合
        List<SpecParam> specParams = itemClient.findSpecParams(null, spuDTO.getCid3(), true);
        //通过SpuDTO对象的id查询SpuDetail对象
        SpuDetail spuDetail = itemClient.findSpuDetailById(spuDTO.getId());
        //获取到通用规格参数字段值的字符串类型
        String genericSpecStr = spuDetail.getGenericSpec();
        //将通用规格参数字段值的字符串类型转成map
        Map<Long, Object> genericSpecMap = JsonUtils.toMap(genericSpecStr, Long.class, Object.class);
        //获取到特有规格参数字段值的字符串类型
        String specialSpecStr = spuDetail.getSpecialSpec();
        //将特有规格参数字段值的字符串类型转成map
        Map<Long, List<Object>> specialSpecMap = JsonUtils.nativeRead(specialSpecStr, new TypeReference<Map<Long, List<Object>>>() {});
        //遍历动态过滤条件key所在的对象的集合
        specParams.forEach(specParam -> {
            //获取key值
            String key = specParam.getName();
            //通过判断value的来源获取value值
            Object value = null;
            if(specParam.getGeneric()){
                //通用规格参数
                value = genericSpecMap.get(specParam.getId());
            }else {
                //特有规格参数
                value = specialSpecMap.get(specParam.getId());
            }
            //判断当前过滤条件是否是数值类型
            if(specParam.getNumeric()){
                //将数值兑换成区间
                value = chooseSegment(value, specParam);
            }
            //给结果map中赋值
            filterParamMap.put(key, value);
        });

        //创建Goods对象
        Goods goods = new Goods();
        goods.setId(spuDTO.getId());
        goods.setSubTitle(spuDTO.getSubTitle());
        goods.setSpuName(spuDTO.getName());
        goods.setBrandId(spuDTO.getBrandId());
        goods.setCategoryId(spuDTO.getCid3());
        goods.setCreateTime(spuDTO.getCreateTime().getTime());
        goods.setSkus(JsonUtils.toString(skuList));
        goods.setPrice(prices);
        goods.setAll(all);
        goods.setSpecs(filterParamMap);
        return goods;
    }

    private String chooseSegment(Object value, SpecParam p) {
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 渲染搜索页面数据提供的业务方法
     * @param request
     * @return
     */
    public Map<String, Object> loadSearchPage(SearchRequest request) {
        //分页查询
        PageResult<GoodsDTO> pageResult = itemPageQuery(request);

        //聚合查询
        Map<String, List<?>> filterConditions = aggQuery(request);

        Map<String, Object> result = new HashMap<>();
        result.put("filterConditions", filterConditions);
        result.put("itemsList", pageResult.getItems());
        result.put("totalCount", pageResult.getTotal());
        result.put("totalPages", pageResult.getTotalPage());
        return result;
    }

    /**
     * 渲染过滤条件
     * @param request
     * @return
     */
    public Map<String, List<?>> aggQuery(SearchRequest request) {
        Map<String, List<?>> resultMap = new LinkedHashMap<>();
        //先聚合分类和品牌
        //封装复杂条件和分页对象
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //封装分页条件，在聚合查询时，分页不影响聚合结果，可有可无。
        nativeSearchQueryBuilder.withPageable(PageRequest.of(0, 1));
        //封装要查询的字段，在聚合查询时，查询字段数不影响聚合结果，可有可无。
        nativeSearchQueryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));
        //封装查询条件
        nativeSearchQueryBuilder.withQuery(createQueryParams(request));
        //指定一个分类聚合的名称
        String categoryAgg = "categoryAgg";
        //添加分类的聚合条件  如果要查询更多用.size(Integer.MAX_VALUE)
        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(categoryAgg).field("categoryId"));
        //指定一个品牌聚合的名称
        String brandAgg = "brandAgg";
        //添加品牌的聚合条件
        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(brandAgg).field("brandId"));

        //执行聚合查询
        AggregatedPage<Goods> aggResult = esTemplate.queryForPage(nativeSearchQueryBuilder.build(), Goods.class);

        //得到所有的聚合结果
        Aggregations aggregations = aggResult.getAggregations();
        //根据分类聚合名称获取到分类的聚合结果
        Terms categoryTerms = aggregations.get(categoryAgg);
        //解析分类的聚合结果并将结果放入到结果map中。
        List<Long> cids = handlerCategoryAgg(resultMap, categoryTerms);

        //根据品牌聚合名称获取到品牌的聚合结果
        Terms brandTerms = aggregations.get(brandAgg);
        //解析品牌的聚合结果并将结果放入到结果map中。
        handlerBrandAgg(resultMap, brandTerms);

        //根据分类id查询出要聚合的过滤条件规格参数并将其放入到结果map中
        handlerFilterParamsAgg(resultMap, createQueryParams(request), cids);

        return resultMap;
    }

    /**
     * 根据分类id查询出要聚合的过滤条件规格参数并将其放入到结果map中
     */
    private void handlerFilterParamsAgg(Map<String, List<?>> resultMap, QueryBuilder queryParams, List<Long> cids) {
        cids.forEach(cid->{
            //封装复杂条件和分页对象
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            //封装分页条件，在聚合查询时，分页不影响聚合结果，可有可无。
            nativeSearchQueryBuilder.withPageable(PageRequest.of(0, 1));
            //封装要查询的字段，在聚合查询时，查询字段数不影响聚合结果，可有可无。
            nativeSearchQueryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));
            //封装查询条件
            nativeSearchQueryBuilder.withQuery(queryParams);

            //根据分类id查询该分类下所有参与搜索的规格参数集合
            List<SpecParam> specParams = itemClient.findSpecParams(null, cid, true);
            //遍历
            specParams.forEach(specParam -> {
                //指定聚合的名称
                String specAgg = specParam.getName();
                //得到当前聚合的规格参数的域名称
                String field = "specs."+specAgg+".keyword";
                //添加聚合条件  如果要查询更多用.size(Integer.MAX_VALUE)
                nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(specAgg).field(field));
            });

            //执行聚合查询
            AggregatedPage<Goods> aggResult = esTemplate.queryForPage(nativeSearchQueryBuilder.build(), Goods.class);

            //得到所有的聚合结果
            Aggregations aggregations = aggResult.getAggregations();

            //遍历获取聚合结果
            specParams.forEach(specParam -> {
                //指定聚合的名称
                String specAgg = specParam.getName();
                //获取对应的聚合结果
                Terms specTerms = aggregations.get(specAgg);
                //收集到所有的聚合结果
                List<String> specResult = specTerms.getBuckets()
                        .stream()
                        .map(Terms.Bucket::getKeyAsString)
                        .collect(Collectors.toList());
                //将结果放入结果map中
                resultMap.put(specAgg, specResult);
            });

        });
    }

    /**
     * 解析品牌的聚合结果并将结果放入到结果map中
     */
    private void handlerBrandAgg(Map<String, List<?>> resultMap, Terms brandTerms) {
        List<Long> bids = brandTerms.getBuckets()
                .stream()
                .map(Terms.Bucket::getKeyAsNumber)
                .map(Number::longValue)
                .collect(Collectors.toList());
        //根据品牌id的集合查询品牌对象的集合
        List<Brand> brands = itemClient.findBrandsByIds(bids);
        //将结果放入结果map中
        resultMap.put("品牌", brands);
    }

    /**
     * 解析分类的聚合结果并将结果放入到结果map中
     * @return
     */
    private List<Long> handlerCategoryAgg(Map<String, List<?>> resultMap, Terms categoryTerms) {
        List<Long> cids = categoryTerms.getBuckets()
                .stream()
                .map(Terms.Bucket::getKeyAsNumber)
                .map(Number::longValue)
                .collect(Collectors.toList());
        //根据分类id的集合获取到分类对象的集合
        List<Category> categories = itemClient.findCategoriesByIds(cids);
        //将结果放入结果map中
        resultMap.put("分类", categories);
        return cids;
    }

    /**
     * 渲染分页相关数据
     * @param request
     * @return
     */
    public PageResult<GoodsDTO> itemPageQuery(SearchRequest request) {
        //封装复杂条件和分页对象
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //封装分页条件
        nativeSearchQueryBuilder.withPageable(PageRequest.of(request.getPage()-1, request.getSize()));
        //封装要查询的字段  //"id", "spuName", "subTitle", "skus","createTime" 五个参数都来自于goodslist
        nativeSearchQueryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id", "spuName", "subTitle", "skus"}, null));

        //排序

        String sortBy = request.getSortBy();
        Boolean desc = request.getDescending();
        if (StringUtils.isNotBlank(sortBy)){
            //如果不为空则排序
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(sortBy).order(desc ? SortOrder.DESC : SortOrder.ASC));
        }

        //封装查询条件
        nativeSearchQueryBuilder.withQuery(createQueryParams(request));
        //封装高亮字段
        HighlightUtils.highlightField(nativeSearchQueryBuilder, "spuName");

        //执行复杂条件分页查询
        AggregatedPage<Goods> queryForPage = esTemplate.queryForPage(nativeSearchQueryBuilder.build(), Goods.class, HighlightUtils.highlightBody(Goods.class, "spuName"));

        //获取Goods集合
        List<Goods> goodsList = queryForPage.getContent();
        //判空
        if(CollectionUtils.isEmpty(goodsList)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }


        //将Goods集合转成GoodsDTO集合
        List<GoodsDTO> goodsDTOS = BeanHelper.copyWithCollection(goodsList, GoodsDTO.class);

        //创建一个自定义分页对象
        PageResult<GoodsDTO> pageResult = new PageResult<>(
                queryForPage.getTotalElements(),
                Long.valueOf(queryForPage.getTotalPages()),
                goodsDTOS
        );
        return pageResult;
    }

    /**
     * 封装查询条件的方法
     * @param request
     * @return
     */
    private QueryBuilder createQueryParams(SearchRequest request) {
        //提供一个组合条件对象
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //封装搜索条件查询
        boolQuery.must(QueryBuilders.multiMatchQuery(request.getKey(), "all", "spuName").operator(Operator.AND));
        //封装过滤条件查询
        Map<String, Object> filterParams = request.getFilterParams();
        //判断是否有过滤条件
        if(CollectionUtils.isNotEmpty(filterParams)){
            filterParams.entrySet().forEach(entry->{
                //获取域
                String key = entry.getKey();
                if(StringUtils.equals(key, "分类")){
                    key = "categoryId";
                }else if(!StringUtils.equals(key, "brandId")){
                    key = "specs."+key+".keyword";
                }
                //获取值
                Object value = entry.getValue();
                boolQuery.filter(QueryBuilders.termQuery(key, value));
            });
        }
        return boolQuery;
    }

    /**
     * 切换页码
     * @param request
     * @return
     */
    public List<GoodsDTO> changePage(SearchRequest request) {
        //分页查询
        PageResult<GoodsDTO> pageResult = itemPageQuery(request);
        return pageResult.getItems();
    }

    public void addIndex(Long id) {
        SpuDTO spuDTO = itemClient.findSpuDTOById(id);
        Goods goods = buildGoods(spuDTO);
        searchRepository.save(goods);
    }

    public void delIndex(Long id) {
        searchRepository.deleteById(id);
    }

}